package june.trackerrader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSBroadcastReceiver extends BroadcastReceiver {

	public static final String TAG = "SMSBroadcastReceiver";
	
	@Override
	public void onReceive(Context context, Intent intent) {

		Log.i(TAG, "onReceive() called.");
		
        // check if SMS global event is received
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            Log.i(TAG, "SMS received.");
        
//            // abort this one
//            abortBroadcast();
            
            // parse SMS message
            Bundle bundle = intent.getExtras();
    		Object messages[] = (Object[])bundle.get("pdus");
    		SmsMessage smsMessage[] = new SmsMessage[messages.length];
    		
    		int smsPieces = messages.length;
    		for(int n=0;n<smsPieces; n++)
    		{
    			smsMessage[n] = SmsMessage.createFromPdu((byte[])messages[n]);
    		}	
    		
    		String origNumber = smsMessage[0].getOriginatingAddress();
    		String message = smsMessage[0].getMessageBody().toString();	
    		
    		String tag = "aaaa";
    		
    		try{
    			tag = message.subSequence(0, 6).toString(); 
    		} catch (Exception e) {
				// TODO: handle exception
			}
    		
    		if(tag.equals("target")){
    			
                // abort this one
                abortBroadcast();
                
    			Log.i(TAG, "SMS : " + origNumber + ", " + message);
        		
                // launch another activity
                Intent myIntent = new Intent(context, TrackerRaderActivity.class);
                myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                
                myIntent.putExtra("msg", message);
                myIntent.putExtra("num", origNumber);
                context.startActivity(myIntent);
    		}
        }

	}
	
}
